<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    action="http://localhost:3000/upload/album"
    :limit="1"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :auto-upload="false"
  >
    <template #trigger>
      <el-button type="primary">select file</el-button>
    </template>
    <el-button class="ml-3" type="success" @click="submitUpload"> upload to server </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">limit 1 file, new file will cover the old file</div>
    </template>
  </el-upload>

  <el-button v-if="url" type="success" @click="handleClick">
   {{ url }}</el-button
  >

  <el-button v-if="url" type="success" @click="download">
   流下载</el-button
  >
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { genFileId, UploadFile, UploadFiles } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = files => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const url = ref<string>('/api/upload/export')

const submitUpload = () => {
  upload.value!.submit()
}
const handleSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log(`output->uploadFile`, uploadFile, response, uploadFiles)
}
const handleClick = () => {
  window.location.href = url.value;
}

const useFetch = async (url: string) => {
  const res = await fetch(url).then(res => res.arrayBuffer())
  console.log(res)
  const a = document.createElement('a')
  a.href = URL.createObjectURL(new Blob([res],{
    // type:"image/png"
  }))
  a.download = 'games.zip'
  a.click()
}
 
const download = () => {
  useFetch('/api/upload/stream')
}
</script>
